<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="公司名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="公司状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="公司状态"
            clearable
          >
            <el-option :value="1" label="正常" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetQuery"> <i-ep-refresh />重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['sys:dept:add']"
          type="success"
          @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          v-hasPerm="['sys:dept:delete']"
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除
        </el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="tableList"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column
          prop="name"
          label="公司名称"
          show-overflow-tooltip
          scoped-slot
        >
          <template #header>
            <span
              style="display: inline-block; white-space: nowrap"
              :style="{
                'min-width': renderHeader('公司名称')
              }"
              >公司名称</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="domicile" label="注册地" />
        <el-table-column
          prop="manager"
          label="资质管理同事"
          :scoped-slot="renderHeader"
        />
        <el-table-column prop="isNHTE" label="是否为国家高新技术企业">
          <template #default="scope">
            <el-tag>{{ scope.row.isNHTE ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nhteNumber" label="国高证书编号" />
        <el-table-column prop="isSPSEnterprises" label="是否为专精特新企业">
          <template #default="scope">
            <el-tag>{{ scope.row.isSPSEnterprises ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="spsAppliTime" label="最新认定成功时间" />
        <el-table-column prop="isInnovativeSME" label="是否为创新型中小企业">
          <template #default="scope">
            <el-tag>{{ scope.row.isInnovativeSME ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="smeAppliTime" label="最新认定成功时间" />
        <el-table-column prop="isSMETech" label="是否为科技型中小企业">
          <template #default="scope">
            <el-tag>{{ scope.row.isSMETech ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="smeTechAppliTime" label="最新认定成功时间" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" width="100" />

        <el-table-column label="操作" fixed="right" align="left" width="150">
          <template #default="scope">
            <!-- <el-button
              v-hasPerm="['sys:dept:add']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id, undefined)"
              ><i-ep-plus />新增
            </el-button> -->
            <el-button
              v-hasPerm="['sys:dept:edit']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
              ><i-ep-edit />编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:dept:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <companyAddAndUpdate
      v-if="dialog.visible"
      v-model:visible="dialog.visible"
      :title="dialog.title"
      :id="dialog.id"
      @handle-query="handleQuery"
    />
  </div>
</template>

<script setup lang="ts">
import { deleteCompany, listComapny } from '@/api/company'
import { CompanyVO, CompanyQuery } from '@/api/company/types'

defineOptions({
  name: 'Company',
  inheritAttrs: false
})

const queryFormRef = ref(ElForm)
const loading = ref(false)
const ids = ref<number[]>([])
const total = ref(0)
const queryParams = reactive<CompanyQuery>({
  pageNum: 1,
  pageSize: 10
})
const tableList = ref<CompanyVO[]>()
const dialog = reactive({
  visible: false,
  title: '',
  id: 0
})

/** 查询 */
function handleQuery() {
  loading.value = true
  listComapny(queryParams)
    .then(({ data }) => {
      tableList.value = data.list
      total.value = data.total
    })
    .finally(() => {
      loading.value = false
    })
}

/**重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id)
}

// 表头部重新渲染-设置表头文本一行显示
function renderHeader(label) {
  console.log(123456, label)
  // 新建一个 span
  const span = document.createElement('span')
  // 设置表头名称
  span.innerText = label
  // 设置表头样式
  span.style.fontSize = '14px'
  // 临时插入 document
  document.body.appendChild(span)
  // 重点：获取 span 最小宽度，设置当前列，注意这里加了 20，字段较多时还是有挤压，且渲染后的 div 内左右 padding 都是 10，所以 +20 。（可能还有边距/边框等值，需要根据实际情况加上）
  let minWidth = span.getBoundingClientRect().width + 40
  console.log(minWidth)
  // 移除 document 中临时的 span
  document.body.removeChild(span)
  return minWidth
}

/**
 * 打开弹窗
 *
 * @param id 公司ID
 */
async function openDialog(id?: number) {
  dialog.visible = true
  dialog.id = id || 0
  id ? (dialog.title = '修改公司') : (dialog.title = '新增公司')
}

/** 删除公司 */
function handleDelete(id?: number) {
  const companyIds = [id || ids.value].join(',')

  if (!companyIds) {
    ElMessage.warning('请勾选删除项')
    return
  }

  ElMessageBox.confirm(`确认删除已选中的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCompany(companyIds).then(() => {
      ElMessage.success('删除成功')
      resetQuery()
    })
  })
}

onMounted(() => {
  handleQuery()
})
</script>
